package cn.edu.qvtu.lms02;

import java.sql.*;
//INSERT INTO mysqldemo1 (id, employee, age, salary) VALUES (2, "aa", 22, 15000)
public class DBConnection {
    private static  final String URL="jdbc:mysql://localhost:3306/rjgc231";//地址
    private static  final String USERNAME="root";//数据库登录的用户名
    private static  final String PASSWORD="root";//数据库登录的密码
    private static  final String DRIVERNAME="com.mysql.cj.jdbc.Driver";

    //静态代码块：随着类的加载而执行，因为类只会被加载1次，所以静态代码块也只会被执行1次
    static {
        try {
            Class.forName(DRIVERNAME);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL,USERNAME,PASSWORD);
    }

    public static void close(Connection conn, PreparedStatement pstm, ResultSet rs) {
        close(rs);
        close(pstm);
        close(conn);
    }

    private static void close(ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
            }
        }
    }
    private static void close(PreparedStatement pstm){
        if(pstm!=null){
            try {
                pstm.close();
            } catch (SQLException e) {
            }
        }
    }

    private static void close(Connection conn){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
}
